function removeParameter(my_url) {
	// the last index of the ? sign
	b = my_url.lastIndexOf('?');
	if (b == -1) {
		return my_url;
	} else {
	// slicing from 0 (beginning of string) to b (the # sign)
	return my_url.slice(0,b);
	}
}

function init() {
	$(document).ready(function() {
        // Stuff to do as soon as the DOM is ready
		$('.flash').show();
      }); 
	
	$( "#loginTabs" ).tabs();
	$(".button").button();
	clearEntries();
}


function initGeolocation(){
	if(geo_position_js.init()){
		geo_position_js.getCurrentPosition(success_callback,error_callback,{enableHighAccuracy:true});
	}
	else{
		alert("Functionality not available");
	}

	function success_callback(p)
	{	
		$.post('/CloudContact/UserLocation', "latitude=" + p.coords.latitude.toFixed(4) + "&longtitude=" + p.coords.longitude.toFixed(4), function(data) {
			if (data.startsWith("Error:")){
				alert(data);
			}
		});
		
	}
	
	function error_callback(p)
	{
		alert('error='+p.code);
	}	
}

function initContact() {
	$.gvar = {
			loadStatus : {},
			dialog : $('<div></div>')
			.html('Please select Facebook friend to match this contact<br />' +
			'<a class="button" href="#" onclick="saveFBLink(); return false;">Save</a>')
			.dialog({
			autoOpen: false,
			title: 'Facebook friend',
			modal: true,
			position: [350,100],
			height: 300
			})
	};
	getContact();
	init();
	
}

function syncFaceBook(){
	
//	var str = '[{"contactObject":{"members":{"id":{"value":"100001422865919"},"name":{"value":"Bin Shu"},"first_name":{"value":"Bin"},"last_name":{"value":"Shu"},"link":{"value":"http://www.facebook.com/lemist.shu"},"username":{"value":"lemist.shu"},"gender":{"value":"male"},"locale":{"value":"en_US"}}},"userId":"100001422865919"}]';
//	var matchList = jQuery.parseJSON(str);
//	alert(JSON.stringify(matchList[0].contactObject.members.id.value, replacer));
	
	
	$.get('/CloudContact/SyncFaceBook', "contactId=" + $('input[name="id"]').val(), function(data) {

		if (data.startsWith("Redirect:")) {
		document.location = data.split(":")[1];
		} else if (data.startsWith("Error:")){
		alert(data);
		} else {
			var matchList = jQuery.parseJSON(data);

			$.gvar.dialog.html("Please select friend that is the same person as this contact<div>" + 			
					"<a class=\"contactThumb\" href=\"#\" style=\"text-decoration:none\" onclick=\"changeImage('" + matchList[0].contactObject.members.id.value + "','" + matchList[0].contactObject.members.link.value + "'); return false;\">" +
					"<img class=\"dialogImg\" alt=\"\" src=\"https://graph.facebook.com/" + matchList[0].contactObject.members.id.value + 
					"/picture\" /><label class=\"nameCaption\">" + matchList[0].contactObject.members.name.value + "</label></a></div>"
			);
			$.gvar.dialog.dialog('open');
		// prevent the default action, e.g., following a link
		return false;}
		});
}

function replacer(key, value) {
    if (typeof value === 'number' && !isFinite(value)) {
        return String(value);
    }
    return value;
}

function changeImage(fbId, link) {
	$.post('/CloudContact/SavePhotoFromFacebook', "contactid=" + $('input[name="id"]').val() + "&facebookid=" + fbId, function(data) {
		$('input[name="facebook"]').val(link);
		alert("Image is saved");
		$.gvar.dialog.dialog('close');
	});
}


function getContact() {
	
// Get group list
	$.get('/CloudContact/GoogleContactGroup', function(data) {
		
		var groupList = jQuery.parseJSON(data);

		var firstTab = "";
		for (key in groupList) {
			
			if (firstTab == "") {
				firstTab = groupList[key];
			}
			
			$("#contactList").append("<h3 onclick=\"getContactList('" + groupList[key] + "');\" ><a href=\"#\" id=\"grouplink_" + removeString(groupList[key],"System Group: ") + "\">" + removeString(groupList[key],"System Group: ") + "</a></h3>");
			$("#contactList").append("<div id=\"" + groupId(groupList[key]) + "\"></div>");
			
		}

		getContactList(firstTab);
		$('.flash').show();
	});
	
}

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

function getContactList(groupname) {
	
	if ($.gvar.loadStatus[groupname] != null) {
		return;
	}
	
	$.get('/CloudContact/GoogleContactList', "groupname=" + groupname, function(contactData) {
		
		var contactList = jQuery.parseJSON(contactData);

		for (id in contactList) {
			$("#" + groupId(groupname)).append(
				"<a class=\"contactThumb\" href=\"#\" style=\"text-decoration:none\" onclick=\"checkContactDetail('" + id + "'); return false;\">" +
				"<img id=\"thumbImg\" alt=\"\" src=\"/CloudContact/GoogleLoadImage?id=" + id + "\" /><br />" +
				contactList[id] + "</a><br />");
		}
		
		$(".contactThumb").button();
		
		$("#grouplink_" + groupId(groupname)).text($("#grouplink_" + groupId(groupname)).text() + " (" + Object.size(contactList) + ")");
		
		var active = $( "#contactList" ).accordion( "option", "active" );
		$( "#contactList" ).accordion('destroy').accordion({ collapsible: true, active: active });
		
		if (Object.size(contactList) != 0) {
		$.gvar.loadStatus[groupname] = "loaded";}
	});
}

function checkContactDetail(id){
	$.get('/CloudContact/GoogleContactDetail', "contactid=" + id, function(contactData) {
		$("#map_ad").empty();
		var contact = jQuery.parseJSON(contactData);
		var full_name = contact.full_name;
		var email = contact.email;
		var mobile = contact.mobile_phone;
		var address = contact.address;
		var birthday = contact.birthday;
		var facebook = contact.facebook;
		var notes = contact.notes;
		var contactId = contact.id;
		var lati = contact.lati;
		var longi = contact.longi;
		
		$('input[name="id"]').val(contactId);
		$('input[name="name"]').val(full_name);
		$('input[name="email"]').val(email);
		$('input[name="mobile"]').val(mobile);
		$('input[name="address"]').val(address);
	//	$('input[name="birthday"]').val(birthday);
		$('input[name="facebook"]').val(facebook);
		$('input[name="notes"]').val(notes);		
		updateMap(lati, longi);
		$('#contactImg').attr('src', "/CloudContact/GoogleLoadImage?id=" + contactId);
	});
}

function clearEntries(){
	$('input[name="id"]').val("");
	$('input[name="name"]').val("");
	$('input[name="email"]').val("");
	$('input[name="mobile"]').val("");
	$('input[name="address"]').val("");
	//$('input[name="birthday"]').val("");
	$('input[name="facebook"]').val("");
	$('input[name="notes"]').val("");	
}


function save(){
	$.post('/CloudContact/UpdateContact', 
			"id=" + $('input[name="id"]').val() +
			"&name=" + $('input[name="name"]').val()+
			"&email=" + $('input[name="email"]').val()+
			"&mobile=" + $('input[name="mobile"]').val()+
			"&address=" + $('input[name="address"]').val()+
			"&facebook=" + $('input[name="facebook"]').val()+
			"&notes=" + $('input[name="notes"]').val()
		,
			function(data) {
		if (data == "true") alert("updated!");
	});
}

function groupId(original){
	return removeString(original, "System Group: ").replace(" ", "_");
}

function removeString(original, toBeRemoved) {
	// the last index of the ? sign
	b = original.lastIndexOf(toBeRemoved);
	if (b == -1) {
		return original;
	} else {
	// slicing from 0 (beginning of string) to b (the # sign)
	return original.replace(toBeRemoved, "");
	}
}

function updateMap(lati, longi) {
	if (parseFloat(lati) == 0 && parseFloat(longi) == 0){
		$("#map_ad").append('<p>[ :( No idea. Invite your friend to CloudContact to share location.]</p>');
	}
    var latlng = new google.maps.LatLng(lati, longi);
    var myOptions = {
      zoom: 16,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
    
    var marker = new google.maps.Marker({
        position: latlng, 
        map: map, 
        title:"Your Friend"
    });   
}

function logout() {
	window.location.href = removeParameter("/CloudContact/Logout");
}

String.prototype.startsWith = function(str) {
	return (this.indexOf(str) === 0);
};
